﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Shapes;

namespace Grafika_WPF.Shapes
{
    public class DrawTriangle
    {
        public Point A { get; set; }
        public Point B { get; set; }
        public Point C { get; set; }

        public DrawTriangle(Point a, Point b, Point c)
        {
            this.A = a;
            this.B = b;
            this.C = c;
        }

        public bool Contains(Point p)
        {
            return SameSide(A, B, C, p) &&
                   SameSide(B, C, A, p) &&
                   SameSide(C, A, B, p);
        }

        private bool SameSide(Point l1, Point l2, Point a, Point b)
        {
            double c1 = (l2.X - l1.X)*(a.Y - l1.Y) - (l2.Y - l1.Y)*(a.X - l1.X);
            double c2 = (l2.X - l1.X)*(b.Y - l1.Y) - (l2.Y - l1.Y)*(b.X - l1.X);

            return c1*c2 >= 0;
        }

        // Zwraca abComp i acComp takie, że p = a + abComp*AB + acComp*AC
        public bool GetVectorComponents(Point p, out double abComponent, out double acComponent)
        {
            double abX = B.X - A.X;
            double abY = B.Y - A.Y;
            double acX = C.X - A.X;
            double acY = C.Y - A.Y;
            double t = abY*acX - abX*acY;

            if (t == 0)
            {
                abComponent = 0;
                acComponent = 0;
                return false;
            }

            abComponent = A.X*acY - A.Y*acX - p.X*acY + p.Y*acX;
            abComponent /= t;

            acComponent = -A.X*abY + A.Y*abX + p.X*abY - p.Y*abX;
            acComponent /= t;

            return true;
        }

        public Rect GetBoundingRect()
        {
            var xMin = A.X;
            if (B.X < xMin)
                xMin = B.X;
            if (C.X < xMin)
                xMin = C.X;

            var xMax = A.X;
            if (B.X > xMax)
                xMax = B.X;
            if (C.X > xMax)
                xMax = C.X;

            var yMin = A.Y;
            if (B.Y < yMin)
                yMin = B.Y;
            if (C.Y < yMin)
                yMin = C.Y;

            var yMax = A.Y;
            if (B.Y > yMax)
                yMax = B.Y;
            if (C.Y > yMax)
                yMax = C.Y;

            return new Rect(xMin, yMin, xMax - xMin, yMax - yMin);
        }
    }
}
